package Client;

import java.rmi.AccessException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;

import General.Product;
import General.ProxyInterface;
import General.ShipInterface;

public class ProductIterator {
	
	private int fCurrentProductIndex;
	private int fCurrentServerIndex;
	private ProxyInterface fClientProxy;
	private ShipInterface fServer;
	
	public ProductIterator(ProxyInterface clientProxy) {
		fCurrentProductIndex = 0;
		fCurrentServerIndex = 0;
		fClientProxy = clientProxy;
	}
	
	public void reset() {
		fCurrentProductIndex = 0;
		fCurrentServerIndex = 0;
		fServer = null;
	}
	
	public Product next() throws AccessException, RemoteException, NotBoundException {
		// first time only
		if ((fCurrentProductIndex == 0) && (fCurrentServerIndex == 0) && (fServer == null)) {
			fServer = fClientProxy.getServer(0);
			fCurrentProductIndex = -1;
			if (fServer == null) {
				return null;
			}
		}
		
		fCurrentProductIndex++;
		Product product = fServer.getComplete(fCurrentProductIndex);

		if (product == null) {
			// Next server
			fCurrentServerIndex++;
			fServer = fClientProxy.getServer(fCurrentServerIndex);
			if (fServer == null) {
				// No servers left
				fCurrentProductIndex = -1;
				return null;
			} else {
				fCurrentProductIndex = 0;
				return fServer.getComplete(0);
			}
		} else {
			return product;
		}
	}
}
